<?php
namespace App\Repositories;




use App\Models\Coach;
use App\Models\Comment;
use App\Models\Evaluate;
use App\Models\PutPeriod;
use App\Models\School;
use App\Models\SchoolConfig;
use App\Models\Student;
use App\Models\StudentCoach;
use App\Models\StudentState;
use App\Models\Style;
use App\Models\Subscribe;
use App\Models\CoachLeave;
use Carbon\Carbon;
use App\Repositories\SubscribesRepository;
use Illuminate\Support\Facades\DB;

class CoachsRepository extends BaseRepository
{
    public $error = '';
    protected  $subscribe;
    public function __construct(
        Coach $coach,
        SubscribesRepository $subscribe
    )
    {
        $this->model = $coach;
        $this->subscribe = $subscribe;
    }

    /**
     * 资源列表
     * @param  array $param 必须传入与模型查询相关的数据
     * @param  string|array $extra 可选额外传入的参数
     * @param  string $size 分页大小（存在默认值）
     * @return Illuminate\Support\Collection
     */
    public function index($param=[], $extra='', $size='10')
    {

    }


    /**
     * 查询教练详情
     * @param $id
     * @return array
     */
    public function getByInfo($student_info,$id)
    {
        $coach = $this->model->where('id',$id)->select('id','school_id','name','coachnum','photo','sex','idcard','mobile','address','teachpermitted')->first();
        if($coach){
            $coach->evaluateNum = Comment::where('coach_id', $coach->id)->count();

            $evaluate_perfect = Comment::where('comment', 2)->where('coach_id', $coach->id)->count();
            $evaluate_good = Comment::where('comment', 1)->where('coach_id', $coach->id)->count();
            $evaluate_normal = Comment::where('comment', 0)->where('coach_id', $coach->id)->count();
            $coach->evaluationrate =   $coach->evaluateNum ? number_format(($evaluate_good + $evaluate_perfect) /  $coach->evaluateNum,2) : 0;


            $evaluate = Comment::where('coach_id', $coach->id)->take(3)->get()->toArray();
            foreach ($evaluate as $k=>$v){
                $student = Student::where('id',$v['student_id'])->first();
                $evaluate[$k]['stuname'] = $student?$student->name:'';
                $evaluate[$k]['stuphoto'] = $student?$student->photo:'';
            }
            $coach->evaluate = $evaluate;
            $startime = time();
            $endtime = strtotime(date('Y-m-d 23:59:59'));
            $putime = PutPeriod::where('school_id',$coach->school_id)->where('coach_id',$id)->whereBetween('startime',[$startime,$endtime])->get();

            if(count($putime)){
                foreach($putime as $put){
                    $put->student_list = Subscribe::leftJoin('students', 'students.id', '=', 'yy_subscribes.student_id')
                                                        ->select('students.name','students.photo','students.id')
                                                        ->where('yy_subscribes.status', '!=', '3')
                                                        ->where('yy_subscribes.putime_id', $put->id)->take(4)->get();
                    $put->price = $this->subscribe->getPrice($student_info, $put);
                    $put->ssms = $student_info->service->paymode;
                }
            }

            $coach->putime = $putime;

            $coach_style = Style::where('type',2)->where('item_id',$coach->id)->first();

            $coach->description = $coach_style ? $coach_style->content : '';
            $coach->style_pic = $coach_style ? json_decode($coach_style->pic) : [];
        }
        return $coach;

    }


    /**
     * 存储odb
     * @param $inputs
     */
    public function store($inputs, $extra = '')
    {

    }


    /**
     * 更新
     * @param $id
     * @param $input
     * @return mixed
     */
    public function update($id, $input,$extra = '')
    {
        $model = $this->getById($id);
        return $this->save($model,$input);
    }


    /**
     * 编辑特定id资源
     * @param  int $id 资源id
     * @param  string|array $extra 可选额外传入的参数
     * @return Illuminate\Support\Collection
     */
    public function edit($id, $extra)
    {

    }

    /**
     * @param $model
     * @param $inputs
     * @param bool $falg
     * @return mixed
     */
    public function save($model , $inputs , $falg = false)
    {
        return $model;
    }


    /**
     * 教练资料
     */
    public function profile(Coach $coach)
    {
        $coach->school_name = School::find($coach->school_id)->name;
        return $coach;
    }

    public function getCoachLeave($coach_id)
    {
        return CoachLeave::where('item_id',$coach_id)->orderBy('id','desc')->get();
    }
    public function addLeave($data)
    {
        $leave_count = CoachLeave::where('item_id', $data['item_id'])->where(function($q) use ($data) {
                $q->whereRaw("(`startime` >= '{$data['startime']}' and `startime` <='{$data['endtime']}') or (`endtime` >= '{$data['startime']}' and `endtime` <='{$data['endtime']}') or (`endtime` <= '{$data['endtime']}' and `startime` >='{$data['startime']}')");
            })->where('isstate','!=',2)->count();
        if($leave_count){
            return false;
        }
        return CoachLeave::insert($data);
    }


    /**
     * 教练学时预约信息列表
     * @param $coach_id
     * @param $date
     */
    public function coachPeriod($coach_id, $date)
    {
        $start_time = strtotime($date);
        $end_time = $start_time + 86399;

        $period_list = PutPeriod::whereBetween('startime', [$start_time, $end_time])
                                ->where('coach_id', $coach_id)->orderBy('startime')->get();

        if($period_list){

            foreach ($period_list as $period){

                $period->stu_list = Subscribe::leftJoin('students', 'students.id', '=', 'yy_subscribes.student_id')
                                            ->select('yy_subscribes.*','students.name as student_name','students.photo','students.phone')
                                            ->where('yy_subscribes.status','!=',3)
                                            ->where('putime_id',$period->id)->get();
            }
        }

        return $period_list;

    }


    public function coachList(School $school, $type = 1, $page = 1, $size = 15)
    {

        if($type == 1){

            $coach_list = $this->model->select('photo','name','id',DB::raw('(select sum(sum_period) from jx_yy_put_periods where coach_id = jx_coachs.id) as total'))
                                ->where('school_id', $school->id)
                                ->limit($size)->offset(($page - 1) * $size)->orderBy('total', 'desc')->get();
        } elseif ($type == 2){

            $coach_list = $this->model->select('photo','name','id',DB::raw('(select count(distinct(stuid)) from jx_student_coach where cid = jx_coachs.id) as total'))
                ->where('school_id', $school->id)
                ->limit($size)->offset(($page - 1) * $size)->orderBy('total', 'desc')->get();
        } elseif ($type == 3){

            $coach_list = $this->model->select('photo','name','id',DB::raw('(select count(id) from jx_comments where coach_id = jx_coachs.id and comment >= 2) / (select count(id) from jx_comments where coach_id = jx_coachs.id) as total'))
                ->where('school_id', $school->id)
                ->limit($size)->offset(($page - 1) * $size)->orderBy('total', 'desc')->get();

            if($coach_list){
                foreach ($coach_list as $coach){
                    $coach->total = $coach->total ? number_format($coach->total,2) : 0;
                }
            }
        } elseif ($type == 4){

            $coach_list = $this->model->select('photo','name','id',DB::raw('(select count(id) from jx_student_state where coach_id = jx_coachs.id) as total'))
                ->where('school_id', $school->id)
                ->limit($size)->offset(($page - 1) * $size)->orderBy('total', 'desc')->get();
        } elseif ($type == 5) {

            $coach_list = $this->model->select('photo','name','id',DB::raw('(select sum(duration) from jx_tcp_studytimes where coachnum = jx_coachs.coachnum) as total'))
                ->where('school_id', $school->id)
                ->limit($size)->offset(($page - 1) * $size)->orderBy('total', 'desc')->get();

            if($coach_list){
                $school_config = SchoolConfig::where('school_id', $school->id)->first();
                $per_hour = 45;
                if($school_config && $school_config->sch_putime_length){
                    $per_hour = $school_config->sch_putime_length;
                }

                foreach ($coach_list as $coach){
                    $coach->total = $coach->total ? number_format($coach->total / $per_hour, 2) : 0;
                }
            }
        } elseif ($type == 6){

            $coach_list = $this->model->select('photo','name','id',DB::raw('(select 0) as total'))
                ->where('school_id', $school->id)
                ->where('ischeck', 0)
                ->limit($size)->offset(($page - 1) * $size)->orderBy('total', 'desc')->get();

        }

        return $coach_list;
    }
}